package com.liuqi.aiagent.controller;

import com.alibaba.fastjson.JSONObject;
import com.liuqi.aiagent.ai.tool.WebHookJsonSchema;
import com.liuqi.aiagent.service.WebhookToolService;
import com.liuqi.aiagent.transfer.ApiResult;
import com.liuqi.aiagent.transfer.dto.WebhookToolSaveDto;
import com.liuqi.aiagent.transfer.model.Result;
import com.liuqi.aiagent.transfer.model.ResultList;
import com.liuqi.aiagent.transfer.vo.WebhookToolBriefVo;
import com.liuqi.aiagent.transfer.vo.WebhookToolVo;
import com.liuqi.aiagent.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author liuqi
 * @date 2025/7/15
 **/
@RestController
@RequestMapping("/tool/webhook")
@AllArgsConstructor
@Api(tags = "WebHook外部工具服务接口")
@Slf4j
public class WebhookToolController {

    private final WebhookToolService webhookToolService;

    @PostMapping("/imports")
    @ApiOperation(value = "WebHook工具上传")
    @ApiImplicitParam(name = "file", value = "file", required = true, dataTypeClass = MultipartFile.class)
    public Result imports(@RequestParam("file") MultipartFile file) {
        String content;
        try {
            content = new String(file.getBytes(), StandardCharsets.UTF_8);
            if (StringUtil.notHasText(content)) {
                return ApiResult.fail( "文件内容为空");
            }
        } catch (IOException e) {
            log.error("上传webhook工具失败. 读取文件异常", e);
            return ApiResult.fail( "文件上传失败");
        }

        List<WebHookJsonSchema> schemas;

        try {
            schemas = JSONObject.parseArray(content, WebHookJsonSchema.class);
        } catch (Throwable t) {
            log.error("上传webhook失败. json文件解析失败", t);
            return ApiResult.fail( "json文件解析失败");

        }

        // to WebhookToolSaveDto
        List<WebhookToolSaveDto> webhookTools = new ArrayList<>();
        for (WebHookJsonSchema schema : schemas) {
            String groupName = schema.getGroupName();
            List<String> servers = schema.getServers();
            Map<String, String> headers = schema.getHeaders();
            String contentType = schema.getContentType();
            List<WebHookJsonSchema.Paths> paths = schema.getPaths();

            if (StringUtil.notHasText(groupName)) {
                log.error("上传webhook工具失败, groupName 为空. schema = " + JSONObject.toJSONString(schema));
                return ApiResult.fail( "groupName 为空");
            }
            if (servers == null || servers.isEmpty()) {
                log.error("上传webhook工具失败, servers 为空. schema = " + JSONObject.toJSONString(schema));
                return ApiResult.fail( "servers 为空");
            }
            if (StringUtil.notHasText(contentType)) {
                log.error("上传webhook工具失败, content_type 为空. schema = " + JSONObject.toJSONString(schema));
                return ApiResult.fail( "content_type 为空");
            }
            if (paths == null || paths.isEmpty()) {
                log.error("上传webhook工具失败, paths 为空. schema = " + JSONObject.toJSONString(schema));
                return ApiResult.fail( "paths 为空");
            }

            // to WebhookToolSaveDto
            for (WebHookJsonSchema.Paths path : paths) {
                String p = path.getPath();
                String name = path.getName();
                String description = path.getDescription();

                if (StringUtil.notHasText(p)) {
                    log.error("上传webhook工具失败. paths.path 为空. path = " + JSONObject.toJSONString(path));
                    return ApiResult.fail( "paths.path 为空");
                }
                if (StringUtil.notHasText(name)) {
                    log.error("上传webhook工具失败. paths.name 为空. path = " + JSONObject.toJSONString(path));
                    return ApiResult.fail( "paths.name 为空");
                }
                if (StringUtil.notHasText(description)) {
                    log.error("上传webhook工具失败. paths.description 为空. path = " + JSONObject.toJSONString(path));
                    return ApiResult.fail( "paths.description 为空");
                }

                WebhookToolSaveDto webhookToolSaveDto = WebhookToolSaveDto.builder()
                        .groupName(groupName)
                        .servers(JSONObject.toJSONString(servers))
                        .headers(JSONObject.toJSONString(headers))
                        .contentType(contentType)
                        .path(path.getPath())
                        .toolName(name)
                        .description(description)
                        .function(path.toAiFunctionString(groupName))
                        .build();

                webhookTools.add(webhookToolSaveDto);
            }
        }

        return webhookToolService.imports(webhookTools);
    }

    @GetMapping("/download/template")
    @ApiOperation(value = "WebHookTool工具描述模板文件")
    public ResponseEntity<Resource> downloadTemplate() {
        ClassPathResource resource = new ClassPathResource("webhook-template.json");
        // 3. 设置响应头
        String contentType = "application/json";
        String headerValue = "attachment; filename=\"" + resource.getFilename() + "\"";
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
                .body(resource);
    }

    @GetMapping("/findAll")
    @ApiOperation(value = "查询所有Webhook工具")
    public ResultList<WebhookToolVo> findAll() {
        return webhookToolService.findAll();
    }

    @GetMapping("/findAllOfBrief")
    @ApiOperation(value = "查询所有Webhook工具, 返回简要信息")
    public ResultList<WebhookToolBriefVo> findAllOfBrief() {
        return webhookToolService.findAllOfBrief();
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除WebHookTool工具")
    @ApiImplicitParam(name = "id", value = "WebHookToll ID", required = true, dataTypeClass = Integer.class)
    public Result delete(Integer id) {
        if (id == null) {
            return ApiResult.fail("ID为空");
        }
        return webhookToolService.deleteById(id);
    }

}

